package erwiki.ui.app.parts.attachments.handlers;

import java.util.Collection;

import org.apache.log4j.Logger;
import org.eclipse.e4.core.di.annotations.CanExecute;
import org.eclipse.e4.core.di.annotations.Execute;
import org.eclipse.e4.core.di.annotations.Optional;
import org.eclipse.e4.core.services.events.IEventBroker;
import org.eclipse.e4.ui.model.application.ui.basic.MPart;
import org.eclipse.e4.ui.model.application.ui.menu.MHandledToolItem;
import org.eclipse.e4.ui.services.IServiceConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.elwiki_data.AttachmentContent;

import erwiki.api.attachment.AttachmentManager;
import erwiki.api.auth.AuthorizationManager;
import erwiki.api.exceptions.ProviderException;
import erwiki.ui.app.parts.attachments.EventsAttachmentsView;
import erwiki.ui.app.parts.attachments.WikiAttachmentsView;
import jakarta.inject.Inject;
import jakarta.inject.Named;

public class DeleteAttachmentHandler {

	private static final Logger log = Logger.getLogger(DeleteAttachmentHandler.class);

	@Inject
	AttachmentManager attachmentManager;

	@Inject
	AuthorizationManager authorizationManager;

	@Inject
	IEventBroker eventBroker;

	/**
	 * Удаляет прикрепления, выбранные в WikiAttachmentsView.
	 *
	 * @param shell
	 * @param activePart
	 */
	@Execute
	public void deleteAttachment(@Named(IServiceConstants.ACTIVE_SHELL) Shell shell,
			@Named(IServiceConstants.ACTIVE_PART) MPart activePart, MHandledToolItem mitem) {
		System.err.println(mitem.getElementId());

		if (activePart.getObject() instanceof WikiAttachmentsView wikiAttachmentsView) {
			boolean isRemove = MessageDialog.openQuestion(shell, "Warning",
					"Are you sure you need to delete the selected attachment?");
			Collection<AttachmentContent> selectedAttachments = wikiAttachmentsView.getSelectedAttachments();
			if (isRemove && selectedAttachments.size() > 0) {
				for (AttachmentContent atchContent : selectedAttachments) {
					try {
						attachmentManager.deleteAttachmentContent(atchContent);
					} catch (ProviderException e) {
						log.error("Fail delete AttachmentContent item", e);
					}
				}
				eventBroker.post(EventsAttachmentsView.TOPIC_ATTACHMENTS_UPDATE, "updated");
			}
		}
	}

	@CanExecute
	public boolean canExecute(@Named(IServiceConstants.ACTIVE_SELECTION) @Optional ISelection selection,
			@Named(IServiceConstants.ACTIVE_PART) MPart activePart) {
		if (activePart.getObject() instanceof WikiAttachmentsView wikiAttachmentsView //
				&& selection instanceof IStructuredSelection ss //
				&& ss.getFirstElement() instanceof AttachmentContent) {
			return true;
		}

		return false;
	}

}
